package com.ultrapower.ctool.xn_app;

import android.content.Intent;
import android.content.pm.PackageManager;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.ultrapower.ctool.core.CustomApplication;
import com.ultrapower.ctool.http.BaseActivity;
import com.ultrapower.ctool.utils.SerializableMap;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class MainActivity extends BaseActivity implements View.OnClickListener{
    public LocationClient mLocationClient;

    private TextView username_top;//顶部展示的用户名称

    private TextView location;//用户当前位置

    private LinearLayout  jingying;//经营单位

    private LinearLayout wangge;//网格事件

    private LinearLayout richang;//日常巡查

    private LinearLayout zhuanxiang;//专项巡查

    private LinearLayout  wanggeOther;//网格信息

    private LinearLayout userinfoOther;//个人中心

    private LinearLayout systemOther;//系统管理

    private ImageView locationImgButton;//定位

    private String userInfo;
    private CustomApplication application;
    private Map<String,Object> menuMap;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        init();
        Intent intent = getIntent();
        application = (CustomApplication) getApplication();
        userInfo=application.getLoginUser().getNickname();
        TextView lblTitle=(TextView)findViewById(R.id.username_top);
        lblTitle.setText((userInfo==null?"":userInfo)+lblTitle.getText());
        menuMap=((SerializableMap)intent.getSerializableExtra("menu")).getMap();
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.m_aj_jydw://经营单位
                if(menuMap.containsKey("m_aj_jydw")) {
                    Intent intent1 = new Intent(MainActivity.this, JingYingActivity.class);
                    startActivity(intent1);
                }else{
                    Toast.makeText(this, "没有相关权限", Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.m_aj_sj_mgr://网格事件
                if(menuMap.containsKey("m_aj_sj_mgr")) {
                    Intent intent2 = new Intent(MainActivity.this, WangGeActivity.class);
                    startActivity(intent2);
                }else{
                    Toast.makeText(this, "没有相关权限", Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.m_aj_rcxc://日常巡查
                if(menuMap.containsKey("m_aj_rcxc")) {
                    Intent intent3 = new Intent(MainActivity.this, RiChangeActivity.class);
                    startActivity(intent3);
                }else{
                    Toast.makeText(this, "没有相关权限", Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.m_aj_zxxc://专项巡查
                if(menuMap.containsKey("m_aj_zxxc")) {
                    Intent intent4 = new Intent(MainActivity.this, ZhuanXiangActivity.class);
                    startActivity(intent4);
                }else{
                    Toast.makeText(this, "没有相关权限", Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.m_aj_wgxx://网格信息
                if(menuMap.containsKey("m_aj_wgxx")) {
                    Intent intent5 = new Intent(MainActivity.this, WangGeXXActivity.class);
                    startActivity(intent5);
                }else{
                    Toast.makeText(this, "没有相关权限", Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.userinfoOther://个人中心
                Intent intent6 = new Intent(MainActivity.this,UserCenterActivity.class);
                startActivity(intent6);
                break;
            case R.id.systemOther://系统管理
                Intent intent7 = new Intent(MainActivity.this,SystemOtherActivity.class);
                startActivity(intent7);
                break;
            case R.id.locationImgButton://定位
                mLocationClient= new LocationClient(getApplicationContext());
                mLocationClient.registerLocationListener(new MyLocationListener());
                List<String> permissionList = new ArrayList<>();
                if(ContextCompat.checkSelfPermission(MainActivity.this, android.Manifest.permission.ACCESS_FINE_LOCATION)
                        != PackageManager.PERMISSION_GRANTED){
                    permissionList.add(android.Manifest.permission.ACCESS_FINE_LOCATION);
                }
                if(ContextCompat.checkSelfPermission(MainActivity.this, android.Manifest.permission.READ_PHONE_STATE)
                        != PackageManager.PERMISSION_GRANTED){
                    permissionList.add(android.Manifest.permission.READ_PHONE_STATE);
                }
                if(ContextCompat.checkSelfPermission(MainActivity.this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
                        != PackageManager.PERMISSION_GRANTED){
                    permissionList.add(android.Manifest.permission.WRITE_EXTERNAL_STORAGE);
                }
                if(!permissionList.isEmpty()){
                    String[] permissions = permissionList.toArray(new String[permissionList.size()]);
                    ActivityCompat.requestPermissions(MainActivity.this,permissions,1);
                }else{
                    location.setText("正在定位,请稍等...");
                    requestLocation();
                }
                break;
        }
    }

    private void requestLocation() {
        initLocation();
        mLocationClient.start();
    }

    private void initLocation() {
        LocationClientOption option = new LocationClientOption();
        option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy
        );//可选，默认高精度，设置定位模式，高精度，低功耗，仅设备
        option.setCoorType("bd09ll");//可选，默认gcj02，设置返回的定位结果坐标系
//        int span = 1000;
//        option.setScanSpan(span);//可选，默认0，即仅定位一次，设置发起定位请求的间隔需要大于等于1000ms才是有效的
        option.setIsNeedAddress(true);//可选，设置是否需要地址信息，默认不需要
//        option.setOpenGps(false);//可选，默认false,设置是否使用gps
//        option.setLocationNotify(false);//可选，默认false，设置是否当GPS有效时按照1S/1次频率输出GPS结果
        option.setIsNeedLocationDescribe(true);//可选，默认false，设置是否需要位置语义化结果，可以在BDLocation.getLocationDescribe里得到，结果类似于“在北京天安门附近”
//        option.setIsNeedLocationPoiList(false);//可选，默认false，设置是否需要POI结果，可以在BDLocation.getPoiList里得到
//        option.setIgnoreKillProcess(false);//可选，默认true，定位SDK内部是一个SERVICE，并放到了独立进程，设置是否在stop的时候杀死这个进程，默认不杀死
        option.SetIgnoreCacheException(false);//可选，默认false，设置是否收集CRASH信息，默认收集
//        option.setEnableSimulateGps(false);//可选，默认false，设置是否需要过滤GPS仿真结果，默认需要
        mLocationClient.setLocOption(option);
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode){
            case 1:
                if (grantResults.length>0){
                    for(int result:grantResults){
                        if(result != PackageManager.PERMISSION_GRANTED){
                            Toast.makeText(this, "无定位权限", Toast.LENGTH_SHORT).show();
                            return;
                        }
                    }
                    requestLocation();
                }else{
                    Toast.makeText(this, "发生未知错误", Toast.LENGTH_SHORT).show();
                    return;
                }
            default:
        }
    }

    public void init(){
        username_top = (TextView)findViewById(R.id.username_top);
        location = (TextView)findViewById(R.id.location);
        jingying = (LinearLayout)findViewById(R.id.m_aj_jydw);
        wangge = (LinearLayout)findViewById(R.id.m_aj_sj_mgr);
        richang = (LinearLayout)findViewById(R.id.m_aj_rcxc);
        zhuanxiang = (LinearLayout)findViewById(R.id.m_aj_zxxc);
        wanggeOther = (LinearLayout)findViewById(R.id.m_aj_wgxx);
        userinfoOther = (LinearLayout)findViewById(R.id.userinfoOther);
        systemOther = (LinearLayout)findViewById(R.id.systemOther);
        locationImgButton = (ImageView) findViewById(R.id.locationImgButton);
        jingying.setOnClickListener(this);
        wangge.setOnClickListener(this);
        richang.setOnClickListener(this);
        zhuanxiang.setOnClickListener(this);
        wanggeOther.setOnClickListener(this);
        userinfoOther.setOnClickListener(this);
        systemOther.setOnClickListener(this);
        locationImgButton.setOnClickListener(this);
    }

    public class MyLocationListener implements BDLocationListener{

        @Override
        public void onReceiveLocation(final BDLocation bdLocation) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    StringBuilder sb = new StringBuilder();
                    if(bdLocation.getLongitude()==0||bdLocation.getLatitude()==0||
                            bdLocation.getCity()==null||bdLocation.getDistrict()==null||
                            bdLocation.getStreet()==null){
                        location.setText("网络繁忙,请稍后再试");
                    }else{
                        sb.append("经度：").append(bdLocation.getLongitude()+";");
                        sb.append("纬度：").append(bdLocation.getLatitude()+";");
                        sb.append("您所在的位置：").append(bdLocation.getCity()+"市"+
                                bdLocation.getDistrict()+"区"+bdLocation.getStreet());
                        location.setText(sb.toString());
                    }

                }

            });
        }

        @Override
        public void onConnectHotSpotMessage(String s, int i) {

        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(mLocationClient != null){
            mLocationClient.stop();
        }
    }
}
